<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>商品套餐管理</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		#showGoodsList{
			position:fixed;
			padding:10px 15px;
			width:800px;
			height:300px;
			background:#FFF;
			top:10%;
			left:15%;
			margin:0 auto;
			border:1px solid #CCC;
			box-shadow:3px 3px 10px 4px #DDD;
			z-index: 999;
		}
		.goods_list_td{
			margin-left:5px;
		}
	</style>
	<script type="text/javascript">
		var checkedGoods = [];
		var subFlag = true;
		var deleteDetail = "";
		Dropzone.autoDiscover = false;
		var detailUpdateState = false;
		$(document).ready(function() {
			$('#showCheckList').find('label').each(function(e,v){
				var value = $(v).attr('id').substring(6);
				checkedGoods.push(value)
			})
			searchGoods();
			getTwiceClass();
			getThirdClass()
			$("#inputForm").validate({
				submitHandler: function(form){
					if(subFlag){
						subFlag = false;
						var photoSrc = $("#photo").val();
						if(photoSrc == ""){
							$("#imgPhotoDiv").after("<label for='photo' id='errorPhotoLabel' style='margin-top:100px;' class='error'>请上传图片</label>")
							subFlag = true;
							return false;
						}
						if(detailDropzone.getQueuedFiles().length == 0){
							detailUpdateState = true;						
						}
						detailDropzone.processQueue();
						$("#deleteDetail").val(deleteDetail);
						var clock = setInterval(function(){
							if(detailUpdateState){
								clearInterval(clock);
								loading('正在提交，请稍等...');
								form.submit();
							}else{
								loading('正在提交，请稍等...');
							}
						}, 500); //所有图片处理完成才执行表单提交
					}else{
						loading('正在提交，请稍等...');
					}
				},
				rules:{          
					name:{required:true,stringCheck:true}, 
					num:{digits:true},
					goodsPrice:{isPrice:true},
					price:{required:true}
	            },
				messages:{
					name:{required:"请输入套餐名称"},
					price:{required:"至少选择一件商品"}
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.appendTo(element.parent());
					}
				}
			});
			jQuery.validator.addMethod("isPrice", function(value, element) {
				return this.optional(element) || /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/.test(value);
			}, "请输入正确金额");
			// 字符验证
			jQuery.validator.addMethod("stringCheck", function(value, element) {
				return this.optional(element) || /^(?![0-9]+$)[\d\D]{4,15}$/.test(value);
			}, "请输入4-15个字符，须含汉字或字母，可带数字和标点符号");
			//商品详情图片
			var detailDropzone = new Dropzone("#detailDiv",{
				url : "${ctx}/sys/goodsCombo/saveDetail",//请求地址
				maxFiles : 5,//最大文件数
				maxFilesize : 5,//限制文件大小,MB为单位
				addRemoveLinks : true,//显示删除按钮
				dictRemoveFile : "删除",//上传成功后显示的内容
				dictCancelUpload : "", //正在上传中显示的内容
				acceptedFiles : ".jpg", //允许上传的格式
				dictDefaultMessage : "点击此处或者拖拽文件到此处上传,最多5张图片",
				dictInvalidInputType : "不支持的文件类型",
				dictFileTooBig : "文件过大({{filesize}}MB). 上传文件最大支持: {{maxFilesize}}MB",
				dictMaxFilesExceeded : "超过上传数量限制",
				uploadMultiple : true,
				autoProcessQueue : false,//关闭自动提交
				parallelUploads:5,//手动触发上传时一次提交的文件数
				init : function() {//自定义事件
					this.on("removedfile",function(file){//删除文件时如果删除的是回选文件则上传数上限+1.
						console.log('删除了一张'+deleteDetail+":"+file.name);
						if(file.name.substring(0,4) == "AUTO"){
							 this.options.maxFiles = detailDropzone.options.maxFiles + 1;
							 deleteDetail += file.name.substring(5,file.name.length)+";";
						}
					});
					this.on("queuecomplete",function(){//列队上传完毕执行
						detailUpdateState = true;
					});
					var images = "${goodsCombo.remarks}".split(";");
					var maxLength = 0;
					if(images.length == 1 && images[0] == ""){
						maxLength = 0;
					}else{
						maxLength = images.length;
					}
					for (i = 0; i < images.length; i++) {
						if (images[i] != "") {
							var fileName ="AUTO_"+images[i].substring(images[i].lastIndexOf("/")+1,images[i].lastIndexOf("."));
							var mockFile = {
								name : fileName,
								size : 0,
								type : 'image/jpeg',
								status : Dropzone.ADDED
							};
							this.emit("addedfile", mockFile);
							this.emit("thumbnail", mockFile, images[i]);
							this.emit("complete", mockFile);
							this.files.push(mockFile);
						}
					}
					this.options.maxFiles = this.options.maxFiles - maxLength;
				}
			});
			
			$("#showGoodsList").on('click','input[name="fdId"]',function(){
				var v=$(this).val();
				if ($.inArray(v,checkedGoods)==-1){
					checkedGoods.push(v);
				}else{
					for(var i=0;i<=checkedGoods.length-1;i++){
						if(checkedGoods[i]==v){
							checkedGoods.splice(i,1);
						}
					}
				}
			})
			$("#showGoodsList").on('click','#checkAll',function(){
				$("input[name='fdId']").each(function(e,v){
					var value = $(v).val()
					if($('#checkAll').is(':checked')){
						this.checked = true;
						if ($.inArray(value,checkedGoods)==-1){
							checkedGoods.push(value);
						}
					}else{
						this.checked = false;
						for(var i=0;i<=checkedGoods.length-1;i++){
							if(checkedGoods[i]==value){
								checkedGoods.splice(i,1);
							}
						}
					}
				})
			})
			$("#showCheckList").on('change','input[name="num"],input[name="goodsPrice"]',function(){
				var num = $(this).parent().find('input[name="num"]').val()
				var id = $(this).parent().attr('id').substring(6);
				if(num=='0'){
					deleteGoods(id);
				}else{
					var goodsPrice = $(this).parent().find('input[name="goodsPrice"]').val()
					var sum = parseFloat(num) * parseFloat(goodsPrice);
					$('#sumPrice'+id).val(sum);
				}
				sumAccount();
			})
			$('#inputForm').on("focusin", "#price", function() {
			       $(this).prop('readonly', true);  
			});
	
			$('#inputForm').on("focusout", "#price", function() {
			   $(this).prop('readonly', false); 
			});
		})
		function page(n,s){
			$("#pageNo").val(n);
			$("#pageSize").val(s);
			searchGoods()
        	return false;
        }
		function showPhoto() {
			var r= new FileReader();
			f=document.getElementById('uploadPhoto').files[0];
			r.readAsDataURL(f);
			r.onload=function  (e) {
				document.getElementById('photoImg').src=this.result;
				document.getElementById('photo').value=this.result;
				var src = $("#photo").val();
				if(src != ""){
					$("#errorPhotoLabel").css("display","none");
				}
			};
		}
		function showGoodsList(){
			searchGoods();
			$('#showGoodsList').show();
		}
		function getTwiceClass(){
			var firstId = $('#firstClass').val();
			$.ajax({
				url:'${ctx}/sys/goodsCombo/getClassByParentId',
				data:{'parentId':firstId},
				async:false,
				success:function(result){
					if(result!=null){
						var html = '<option value="">二级类目</option>';
						for(var i = 0;i<result.length;i++){
							var classes = result[i];
							html += '<option value="'+classes.id+'">'+classes.name+'</option>'
						}
						$('#twiceClass').html(html)
					}
				}
			})
		}
		function getThirdClass(){
			var twiceId = $('#twiceClass').val();
			$.ajax({
				url:'${ctx}/sys/goodsCombo/getClassByParentId',
				data:{'parentId':twiceId},
				async:false,
				success:function(result){
					var html = '<option value="">三级类目</option>';
					if(result!=null){
						for(var i = 0;i<result.length;i++){
							var classes = result[i];
							html += '<option value="'+classes.id+'">'+classes.name+'</option>'
						}
						$('#thirdClass').html(html)
					}
				}
			})
		}
		function searchGoods(){
			$.ajax({
				url:'${ctx}/sys/goodsCombo/searchGoods',
				data:$("#searchForm").serialize(),
				async:false,
				success:function(result){
					$("#showGoodsList").html(result)
					$('input[name="fdId"]').each(function(){
						var value = $(this).val();
						for(var i=0;i<=checkedGoods.length-1;i++){
							if(checkedGoods[i]==value){
								this.checked = true;
							}
						}
					})
				}
			})
			return false;
		}
		function closeSearchGoods(){
			$("#showGoodsList").hide();
		}
		function confirmCheckGoods(){
			if(checkedGoods.length==0){
				showTip('至少选择一种商品','',3000,0)
				return false;
			}
			var html = ''
			$.ajax({
				url:'${ctx}/sys/goodsCombo/selectGoodsByIds',
				data:{'checkedGoods':checkedGoods},
				async:false,
				cache : false,
	            traditional: true,
				success:function(result){
					if(result!=null){
						for(var i=0;i<result.length;i++){
							var goods = result[i];
							html += '<label class="control-label" id="label_'+goods.id+'">'+goods.cnName+'：</label>'
							html += '<div class="controls" id="goods_'+goods.id+'">数量：'
							html += '<input name="goodsId" type="hidden" value='+goods.id+'>'
							html += '<input name="goodsCode" type="hidden" value='+goods.code+'>'
							html += '<input name="goodsName" type="hidden" value='+goods.cnName+'>'
							html += '<input name="vipPrice" type="hidden" value='+goods.memberPrice+'>'
							html += '<input name="oldPrice" type="hidden" value='+goods.price+'>'
							html += '<input id="num'+goods.id+'" name="num" type="text" value="1" style="width:50px"/>'
							html += '价格：'
							html += '<input id="goodsPrice'+goods.id+'" name="goodsPrice" type="text" value="'+goods.price+'" style="width:50px"/>'
							html += '<input id="sumPrice'+goods.id+'" class="sumPrice" type="hidden" value="'+goods.price+'" style="width:50px"/>'
							html += '<a onclick="deleteGoods('+goods.id+')">删除</a>';
							html += '</div>';
						}
						$('#showCheckList').html(html);
						$('#showCheckList').show();
						$('#showGoodsList').hide();
						sumAccount()
					}
				}
			})
		}
		function sumAccount(){
			var sum = 0;
			$('.sumPrice').each(function(){
				sum+=parseFloat($(this).val());
			})
			$('#price').val(sum);
		}
		function deleteGoods(id){
			for(var i=0;i<=checkedGoods.length-1;i++){
				if(checkedGoods[i]==id){
					checkedGoods.splice(i,1);
				}
			}
			$('#goods_'+id+'').remove();
			$('#label_'+id+'').remove();
			sumAccount()
		}
	</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/sys/goodsCombo/">商品套餐列表</a></li>
		<li class="active"><a href="${ctx}/sys/goodsCombo/edit?id=${goodsCombo.id}">商品套餐<shiro:hasPermission name="sys:goodsCombo:edit">${not empty goodsCombo.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="sys:goodsCombo:edit">查看</shiro:lacksPermission></a></li>
	</ul><br/>
	<form:form id="inputForm" modelAttribute="goodsCombo" action="${ctx}/sys/goodsCombo/editSave" method="post" class="form-horizontal" enctype="multipart/form-data">
		<form:hidden path="id"/>
		<input type="hidden" name="deleteDetail" id="deleteDetail" />
		<sys:message content="${message}"/>		
		<div class="control-group">
			<label class="control-label">套餐名称：</label>
			<div class="controls">
				<form:input path="name" htmlEscape="false" maxlength="50" class="input-xlarge"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">套餐图片：</label>
			<div class="controls" style="width:200px;height:200px;float:left;margin-left:20px;cursor: pointer;padding:0;border: 2px solid rgba(0, 0, 0, 0.3);" id="imgPhotoDiv">
				<input id="uploadPhoto" alt="" name="file" type="file" style="opacity:0;width:200px;height:200px;position:absolute;z-index:3"  onchange="showPhoto()"/>
   				<img id="photoImg" alt="点击上传图片" src="${goodsCombo.photo}" style="width:200px;height:200px;position:absolute;z-index:2">
			</div>
			<input id="photo" name="photo" value="${goodsCombo.photo}" class="input-xlarge " type="hidden" maxlength="255">
		</div>
		<div class="control-group">
			<label class="control-label">套餐商品：</label>
			<div class="controls">
				<input class="btn btn-primary" type="button" value="选择" onclick="showGoodsList()"/>
			</div>
		</div>
		<c:if test="${not empty goodsCombDetails}">
			<div class="control-group" id="showCheckList">
			<c:forEach items="${goodsCombDetails }" var="goodsCombDetail">
				<label class="control-label" id="label_${goodsCombDetail.goodsId }">${goodsCombDetail.goodsName }：</label>
				<div class="controls" id="goods_${goodsCombDetail.goodsId }">数量：
					<input name="goodsId" type="hidden" value='${goodsCombDetail.goodsId }'>
					<input name="goodsCode" type="hidden" value='${goodsCombDetail.goodsCode }'>
					<input name="goodsName" type="hidden" value='${goodsCombDetail.goodsName }'>
					<input name="vipPrice" type="hidden" value='${goodsCombDetail.vipPrice }'>
					<input name="oldPrice" type="hidden" value='${goodsCombDetail.price }'>
					<input id="num${goodsCombDetail.goodsCombId }" name="num" type="text" value="${goodsCombDetail.num }" style="width:50px"/>
					价格：
					<input id="goodsPrice${goodsCombDetail.goodsId }" name="goodsPrice" type="text" value="${goodsCombDetail.price }" style="width:50px"/>
					<input id="sumPrice${goodsCombDetail.goodsId }" class="sumPrice" type="hidden" value="${goodsCombDetail.price*goodsCombDetail.num }" style="width:50px"/>
					<a onclick="deleteGoods(${goodsCombDetail.goodsId })">删除</a>
				</div>
			</c:forEach>
			</div>
		</c:if>
		<c:if test="${empty goodsCombDetails}">
			<div class="control-group" style="display:none" id="showCheckList">
			
			</div>
		</c:if>
		<div class="control-group">
			<label class="control-label">套餐价格：</label>
			<div class="controls">
				<form:input path="price" htmlEscape="false" class="input-xlarge"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">套餐介绍：</label>
			<div class="controls dropzone" id="detailDiv" style="width: 50%;">

			</div>
		</div>
<%-- 		<div class="control-group">
			<label class="control-label">套餐介绍：</label>
			<div class="controls" style="width:200px;height:200px;float:left;margin-left:20px;cursor: pointer;padding:0;border: 2px solid rgba(0, 0, 0, 0.3);" id="imgPhotoDiv">
				<input id="uploadInfo" alt="" name="file" type="file" style="opacity:0;width:200px;height:200px;position:absolute;z-index:3"  onchange="showInfo()"/>
   				<img id="infoImg" alt="点击上传图片" src="${goodsCombo.remarks}" style="width:200px;height:200px;position:absolute;z-index:2">
			</div>
			<input id="info" name="remarks" value="${goodsCombo.remarks}"  class="input-xlarge " type="hidden" maxlength="255">
		</div> --%>
		<div class="form-actions">
			<shiro:hasPermission name="sys:goodsCombo:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form:form>
	<div style="display:none;z-index:10" id="showGoodsList">
		<form:form id="searchForm" modelAttribute="goods" action="${ctx}/sys/goodsCombo/searchGoods" method="post" class="breadcrumb form-search">
			<input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}"/>
			<input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}"/>
		</form:form>
	</div>
</body>
</html>